﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Log.EventLog;

namespace SE.HTMLRepeater
{
    public partial class MngExistingTemplates : PortalModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bool save = false;

           


            if(!string.IsNullOrEmpty(Request.QueryString["save"]))
            {
                save = Convert.ToBoolean(Request.QueryString["save"]);
            }

            if(save == true)
            {
                string html = this.Settings["template"].ToString();
                txtTemplate.Text = html;
                
            }
            
            if (!IsPostBack)
            {
                LoadTemplateList(null);
                setCommandState();
            }


            
        }

        protected void LoadTemplateList(string Select)
        {
            ddTemplates.Items.Clear();
            string PathToFKCTemplates = getTemplateXmlDocPath();
            if (new System.IO.FileInfo(PathToFKCTemplates).Exists)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(PathToFKCTemplates);
                XmlNodeList xTemplateNodes = xDoc.SelectNodes("/Templates/Template");
                ddTemplates.Items.Add(new ListItem("New", "New"));
                foreach (XmlNode templateNode in xTemplateNodes)
                {
                    string title = templateNode.Attributes.GetNamedItem("title").Value;
                    ddTemplates.Items.Add(new ListItem(title, title));
                }
            }
            else
            {
                // cant find the template xml file security or the fck provider is missing.
                ddTemplates.Items.Add(new ListItem("Error:Can't access template xml file."));

                DotNetNuke.Services.Log.EventLog.LogController LC = new LogController();
                LC.AddLog(new LogInfo("Error:Can't access template xml file." + getTemplateXmlDocPath()));

            }
            if (!string.IsNullOrEmpty(Select))
            {
                ddTemplates.ClearSelection();
                ddTemplates.Items.FindByText(Select).Selected = true;
            }
            setCommandState();



        }

        private void setCommandState()
        {
            if (ddTemplates.SelectedValue != "New")
            {
                cmdSave.CssClass = "CommandButton replace";
                cmdDelete.CssClass = "CommandButton delete";
                cmdDelete.Enabled = true;
            }
            else
            {
                cmdSave.CssClass = "CommandButton";
                cmdDelete.CssClass = "CommandButton";
                cmdDelete.Enabled = false;
            }

        }


        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Globals.NavigateURL(), true);
        }

        private string getTemplateXmlDocPath()
        {
            string temPath = getExtendedXmlSettings("//HTMLRepeaterInfo/Settings/templateFilePath");
            string PathToFKCTemplates = Server.MapPath(temPath);

            

            return PathToFKCTemplates;
        }


        private bool SaveContentAsPermTemplate(string Html,string title, string description, string imageName)
        {

            string PathToFKCTemplates = getTemplateXmlDocPath();
            
            
            try
            {
                if (new System.IO.FileInfo(PathToFKCTemplates).Exists)
                {
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(PathToFKCTemplates);
                    XmlNode xTemplateNode = xDoc.SelectSingleNode("/Templates");
                    XmlNode ExTemplate = xTemplateNode.SelectSingleNode("./Template[@title = '" + title + "']");
                    if (ExTemplate == null)
                    {
                        XmlElement newTemplate = xDoc.CreateElement("Template");
                        XmlAttribute xAT = xDoc.CreateAttribute("title");
                        XmlAttribute xAI = xDoc.CreateAttribute("image");

                        xAT.Value = title;
                        xAI.Value = imageName;

                        newTemplate.Attributes.Append(xAT);
                        newTemplate.Attributes.Append(xAI);

                        newTemplate.InnerXml = "<Description/><Html/>";
                        newTemplate["Description"].InnerText = description;
                        newTemplate["Html"].InnerXml = "<![CDATA[" + Server.HtmlDecode(Html) + "]]>";

                        xTemplateNode.AppendChild(newTemplate);
                    }
                    else
                    {
                        //ExTemplate.Attributes.GetNamedItem("title").Value = title;
                        ExTemplate.Attributes.GetNamedItem("image").Value = imageName;
                        ExTemplate.SelectSingleNode("./Description").InnerText = description;
                        ExTemplate.SelectSingleNode("./Html").InnerXml = "<![CDATA[" + Server.HtmlDecode(Html) + "]]>";
                    }
                    xDoc.Save(PathToFKCTemplates);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
            return true;

        }


        private string getExtendedXmlSettings(string ElementXPath)
        {
            XmlDocument xDoc = new XmlDocument();
            string xmlPath = Server.MapPath(@".\DesktopModules\SE.HTMLRepeater\ExtendedReplacements.xml");
            string TheValue = "";
            if (new System.IO.FileInfo(xmlPath).Exists)
            {
                try
                {
                    xDoc.Load(xmlPath);
                    TheValue = xDoc.SelectSingleNode(ElementXPath).Attributes.GetNamedItem("value").Value.ToString();

                }

                catch (Exception ex)
                {
                    Exceptions.ProcessModuleLoadException(this, ex);
                }
                finally
                {
                    xDoc = null;
                }

            }

            return TheValue;

        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            string Html = txtTemplate.Text;
            string ImagePath = urlImage.Url;

            string baseRootPath = getExtendedXmlSettings("//HTMLRepeaterInfo/Settings/baseRootPath");
            if (ImagePath =="")
            {
                ImagePath = baseRootPath +  "desktopmodules/SE.HTMLRepeater/images/template_thumbnail.png";
            }
            else if (ImagePath.IndexOf('~')== 0)
            {
                //remove the "~/" from the front of the image path.
                ImagePath = baseRootPath + urlImage.Url.Substring(2);
            }else if (ImagePath.IndexOf("FileID") == 0 )
            {
                string fileId = ImagePath.Substring(7);
                
                
                FileController fileController = new FileController();
                FileInfo fileInfo = fileController.GetFileById(Convert.ToInt32(fileId), PortalId);
                ImagePath = baseRootPath + "portals/" + fileInfo.PortalId + "/" + fileInfo.RelativePath;

            }

            SaveContentAsPermTemplate(Html, txTitle.Text, txDescription.Text, ImagePath);
            LoadTemplateList(txTitle.Text);

        }

        protected void ddTemplates_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddTemplates.SelectedValue == "New")
            {
                txTitle.Text = "";
                txDescription.Text = "";
                txtTemplate.Text = "<p>&#160;</p>";
            }
            else
            {
                LoadHTMLTemplate(ddTemplates.SelectedValue);
            }
            setCommandState();
        }

        private void LoadHTMLTemplate(string Name)
        {
            string PathToFKCTemplates = getTemplateXmlDocPath();
            if (new System.IO.FileInfo(PathToFKCTemplates).Exists)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(PathToFKCTemplates);
                XmlNode xTemplateNode = xDoc.SelectSingleNode("/Templates/Template[@title='"+ Name +"']");
                string title = xTemplateNode.Attributes.GetNamedItem("title").Value;
                string image = xTemplateNode.Attributes.GetNamedItem("image").Value;
                string description = xTemplateNode.SelectSingleNode("./Description").InnerText;
                string HTMl = xTemplateNode.SelectSingleNode("./Html").InnerText;


                txtTemplate.Text = HTMl;
                txTitle.Text = title;
                txDescription.Text = description;
                urlImage.Url = image;
            }
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
             string PathToFKCTemplates = getTemplateXmlDocPath();
            string name = ddTemplates.Text;
            if (new System.IO.FileInfo(PathToFKCTemplates).Exists)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(PathToFKCTemplates);
                XmlNode xTemplateNode = xDoc.SelectSingleNode("/Templates/Template[@title='" + name + "']");
                xDoc.SelectSingleNode("Templates").RemoveChild(xTemplateNode);
                xDoc.Save(PathToFKCTemplates);
                LoadTemplateList(null);
                txTitle.Text = "";
                txDescription.Text = "";
                txtTemplate.Text = "<p>&#160;</p>";
            }
        }


    }
}